using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;

namespace PackTracker.Business
{ 
	[Serializable()] 
	public class Veiculo : Csla.BusinessBase<Veiculo>
	{
		#region Business Properties and Methods

		//declare members
		private int _id = 0;
		private string _modelo = string.Empty;
		private string _marca = string.Empty;
		private int _ano = 0;
		private string _placa = string.Empty;
		private int _capacidade = 0;
		private int _idMotorista = 0;

		//declare borrowed child member(s)
		private string _idMotoristaNome;

		[System.ComponentModel.DataObjectField(true, true)]
		public int Id
		{
			get
			{
				CanReadProperty("Id", true);
				return _id;
			}
		}

		public string Modelo
		{
			get
			{
				CanReadProperty("Modelo", true);
				return _modelo;
			}
			set
			{
				CanWriteProperty("Modelo", true);
				if (value == null) value = string.Empty;
				if (!_modelo.Equals(value))
				{
					_modelo = value;
					PropertyHasChanged("Modelo");
				}
			}
		}

		public string Marca
		{
			get
			{
				CanReadProperty("Marca", true);
				return _marca;
			}
			set
			{
				CanWriteProperty("Marca", true);
				if (value == null) value = string.Empty;
				if (!_marca.Equals(value))
				{
					_marca = value;
					PropertyHasChanged("Marca");
				}
			}
		}

		public int Ano
		{
			get
			{
				CanReadProperty("Ano", true);
				return _ano;
			}
			set
			{
				CanWriteProperty("Ano", true);
				if (!_ano.Equals(value))
				{
					_ano = value;
					PropertyHasChanged("Ano");
				}
			}
		}

		public string Placa
		{
			get
			{
				CanReadProperty("Placa", true);
				return _placa;
			}
			set
			{
				CanWriteProperty("Placa", true);
				if (value == null) value = string.Empty;
				if (!_placa.Equals(value))
				{
					_placa = value;
					PropertyHasChanged("Placa");
				}
			}
		}

		public int Capacidade
		{
			get
			{
				CanReadProperty("Capacidade", true);
				return _capacidade;
			}
			set
			{
				CanWriteProperty("Capacidade", true);
				if (!_capacidade.Equals(value))
				{
					_capacidade = value;
					PropertyHasChanged("Capacidade");
				}
			}
		}

		public int IdMotorista
		{
			get
			{
				CanReadProperty("IdMotorista", true);
				return _idMotorista;
			}
			set
			{
				CanWriteProperty("IdMotorista", true);
				if (!_idMotorista.Equals(value))
				{
					_idMotorista = value;
					PropertyHasChanged("IdMotorista");
				}
			}
		}

		public string idMotoristaNome
		{
			get
			{
				CanReadProperty("idMotoristaNome", true);
				return _idMotoristaNome;
			}
		}
 
		protected override object GetIdValue()
		{
			return _id;
		}

		#endregion //Business Properties and Methods

		#region Validation Rules
		private void AddCustomRules()
		{
			//add custom/non-generated rules here...
		}

		private void AddCommonRules()
		{
			//
			// Modelo
			//
			ValidationRules.AddRule(CommonRules.StringRequired, "Modelo");
			ValidationRules.AddRule(CommonRules.StringMaxLength, new CommonRules.MaxLengthRuleArgs("Modelo", 50));
			//
			// Marca
			//
			ValidationRules.AddRule(CommonRules.StringRequired, "Marca");
			ValidationRules.AddRule(CommonRules.StringMaxLength, new CommonRules.MaxLengthRuleArgs("Marca", 50));
			//
			// Placa
			//
			ValidationRules.AddRule(CommonRules.StringRequired, "Placa");
			ValidationRules.AddRule(CommonRules.StringMaxLength, new CommonRules.MaxLengthRuleArgs("Placa", 8));
		}

		protected override void AddBusinessRules()
		{
			AddCommonRules();
			AddCustomRules();
		}
		#endregion //Validation Rules

		#region Authorization Rules
		protected override void AddAuthorizationRules()
		{
			//TODO: Define authorization rules in Veiculo
			//AuthorizationRules.AllowRead("Id", "VeiculoReadGroup");
			//AuthorizationRules.AllowRead("Modelo", "VeiculoReadGroup");
			//AuthorizationRules.AllowRead("Marca", "VeiculoReadGroup");
			//AuthorizationRules.AllowRead("Ano", "VeiculoReadGroup");
			//AuthorizationRules.AllowRead("Placa", "VeiculoReadGroup");
			//AuthorizationRules.AllowRead("Capacidade", "VeiculoReadGroup");
			//AuthorizationRules.AllowRead("IdMotorista", "VeiculoReadGroup");

			//AuthorizationRules.AllowWrite("Modelo", "VeiculoWriteGroup");
			//AuthorizationRules.AllowWrite("Marca", "VeiculoWriteGroup");
			//AuthorizationRules.AllowWrite("Ano", "VeiculoWriteGroup");
			//AuthorizationRules.AllowWrite("Placa", "VeiculoWriteGroup");
			//AuthorizationRules.AllowWrite("Capacidade", "VeiculoWriteGroup");
			//AuthorizationRules.AllowWrite("IdMotorista", "VeiculoWriteGroup");
		}


		public static bool CanGetObject()
		{
			//TODO: Define CanGetObject permission in Veiculo
			return true;
			//if (Csla.ApplicationContext.User.IsInRole("VeiculoViewGroup"))
			//	return true;
			//return false;
		}

		public static bool CanAddObject()
		{
			//TODO: Define CanAddObject permission in Veiculo
			return true;
			//if (Csla.ApplicationContext.User.IsInRole("VeiculoAddGroup"))
			//	return true;
			//return false;
		}

		public static bool CanEditObject()
		{
			//TODO: Define CanEditObject permission in Veiculo
			return true;
			//if (Csla.ApplicationContext.User.IsInRole("VeiculoEditGroup"))
			//	return true;
			//return false;
		}

		public static bool CanDeleteObject()
		{
			//TODO: Define CanDeleteObject permission in Veiculo
			return true;
			//if (Csla.ApplicationContext.User.IsInRole("VeiculoDeleteGroup"))
			//	return true;
			//return false;
		}
		#endregion //Authorization Rules

		#region Factory Methods
		private Veiculo()
		{ /* require use of factory method */ }

		public static Veiculo NewVeiculo()
		{
			if (!CanAddObject())
				throw new System.Security.SecurityException("User not authorized to add a Veiculo");
			return DataPortal.Create<Veiculo>();
		}

		public static Veiculo GetVeiculo(int id)
		{
			if (!CanGetObject())
				throw new System.Security.SecurityException("User not authorized to view a Veiculo");
			return DataPortal.Fetch<Veiculo>(new Criteria(id));
		}

		public static void DeleteVeiculo(int id)
		{
			if (!CanDeleteObject())
				throw new System.Security.SecurityException("User not authorized to remove a Veiculo");
			DataPortal.Delete(new Criteria(id));
		}

		public override Veiculo Save()
		{
			if (IsDeleted && !CanDeleteObject())
				throw new System.Security.SecurityException("User not authorized to remove a Veiculo");
			else if (IsNew && !CanAddObject())
				throw new System.Security.SecurityException("User not authorized to add a Veiculo");
			else if (!CanEditObject())
				throw new System.Security.SecurityException("User not authorized to update a Veiculo");

			return base.Save();
		}

		#endregion //Factory Methods

		#region Child Factory Methods
		internal static Veiculo NewVeiculoChild()
		{
			Veiculo child = new Veiculo();
			child.ValidationRules.CheckRules();
			child.MarkAsChild();
			return child;
		}

		internal static Veiculo GetVeiculo(SafeDataReader dr)
		{
			Veiculo child =  new Veiculo();
			child.MarkAsChild();
			child.Fetch(dr);
			return child;
		}
		#endregion //Child Factory Methods

		#region Data Access

		#region Criteria

		[Serializable()]
		private class Criteria
		{
			public int Id;

			public Criteria(int id)
			{
				this.Id = id;
			}
		}

		#endregion //Criteria

		#region Data Access - Create
		[RunLocal]
		protected override void DataPortal_Create()
		{
			ValidationRules.CheckRules();
		}

		#endregion //Data Access - Create

		#region Data Access - Fetch
		private void DataPortal_Fetch(Criteria criteria)
		{
			using (SqlConnection cn = new SqlConnection(Database.DefaultConnection))
			{
				cn.Open();

				ExecuteFetch(cn, criteria);
			}//using
		}

		private void ExecuteFetch(SqlConnection cn, Criteria criteria)
		{
			using (SqlCommand cm = cn.CreateCommand())
			{
				cm.CommandType = CommandType.StoredProcedure;
				cm.CommandText = "pr_GetVeiculo";
				cm.Parameters.AddWithValue("@id", criteria.Id);

				using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
				{
					dr.Read();
					FetchObject(dr);
					ValidationRules.CheckRules();

					//load child object(s)
					FetchChildren(dr);
				}
			}//using
		}

		#endregion //Data Access - Fetch

		#region Data Access - Insert
		protected override void DataPortal_Insert()
		{
			using (SqlConnection cn = new SqlConnection(Database.DefaultConnection))
			{
				cn.Open();

				ExecuteInsert(cn);

				//update child object(s)
				UpdateChildren(cn);
			}//using

		}

		#endregion //Data Access - Insert

		#region Data Access - Update
		protected override void DataPortal_Update()
		{
			using (SqlConnection cn = new SqlConnection(Database.DefaultConnection))
			{
				cn.Open();

				if (base.IsDirty)
				{
					ExecuteUpdate(cn);
				}

				//update child object(s)
				UpdateChildren(cn);
			}//using

		}

		#endregion //Data Access - Update

		#region Data Access - Delete
		protected override void DataPortal_DeleteSelf()
		{
			DataPortal_Delete(new Criteria(_id));
		}

		private void DataPortal_Delete(Criteria criteria)
		{
			using (SqlConnection cn = new SqlConnection(Database.DefaultConnection))
			{
				cn.Open();

				ExecuteDelete(cn, criteria);

			}//using

		}

		private void ExecuteDelete(SqlConnection cn, Criteria criteria)
		{
			using (SqlCommand cm = cn.CreateCommand())
			{
				cm.CommandType = CommandType.StoredProcedure;
				cm.CommandText = "pr_DeleteVeiculo";

				cm.Parameters.AddWithValue("@id", criteria.Id);

				cm.ExecuteNonQuery();
			}//using
		}
		#endregion //Data Access - Delete

		#region Data Access - Fetch
		private void Fetch(SafeDataReader dr)
		{
			FetchObject(dr);
			MarkOld();
			ValidationRules.CheckRules();

			//load child object(s)
			if(!this.IsChild)
				FetchChildren(dr);
		}

		private void FetchObject(SafeDataReader dr)
		{
			_id = dr.GetInt32("id");
			_modelo = dr.GetString("Modelo");
			_marca = dr.GetString("Marca");
			_ano = dr.GetInt32("Ano");
			_placa = dr.GetString("Placa");
			_capacidade = dr.GetInt32("Capacidade");
			_idMotorista = dr.GetInt32("idMotorista");
			_idMotoristaNome = dr.GetString("idMotoristaNome");
		}

		private void FetchChildren(SafeDataReader dr)
		{
		}
		#endregion //Data Access - Fetch

		#region Data Access - Insert
		internal void Insert(SqlConnection cn)
		{
			if (!IsDirty) return;

			ExecuteInsert(cn);
			MarkOld();

			//update child object(s)
			UpdateChildren(cn);
		}

		private void ExecuteInsert(SqlConnection cn)
		{
			using (SqlCommand cm = cn.CreateCommand())
			{
				cm.CommandType = CommandType.StoredProcedure;
				cm.CommandText = "pr_AddVeiculo";

				AddInsertParameters(cm);

				cm.ExecuteNonQuery();

				_id = (int)cm.Parameters["@id"].Value;
			}//using
		}

		private void AddInsertParameters(SqlCommand cm)
		{
			cm.Parameters.AddWithValue("@Modelo", _modelo);
			cm.Parameters.AddWithValue("@Marca", _marca);
			if (_ano != 0)
				cm.Parameters.AddWithValue("@Ano", _ano);
			else
				cm.Parameters.AddWithValue("@Ano", DBNull.Value);
			cm.Parameters.AddWithValue("@Placa", _placa);
			cm.Parameters.AddWithValue("@Capacidade", _capacidade);
			if (_idMotorista != 0)
				cm.Parameters.AddWithValue("@idMotorista", _idMotorista);
			else
				cm.Parameters.AddWithValue("@idMotorista", DBNull.Value);
			cm.Parameters.AddWithValue("@id", _id);
			cm.Parameters["@id"].Direction = ParameterDirection.Output;
		}
		#endregion //Data Access - Insert

		#region Data Access - Update
		internal void Update(SqlConnection cn)
		{
			if (!IsDirty) return;

			if (base.IsDirty)
			{
				ExecuteUpdate(cn);
				MarkOld();
			}

			//update child object(s)
			UpdateChildren(cn);
		}

		private void ExecuteUpdate(SqlConnection cn)
		{
			using (SqlCommand cm = cn.CreateCommand())
			{
				cm.CommandType = CommandType.StoredProcedure;
				cm.CommandText = "pr_UpdateVeiculo";

				AddUpdateParameters(cm);

				cm.ExecuteNonQuery();

			}//using
		}

		private void AddUpdateParameters(SqlCommand cm)
		{
			cm.Parameters.AddWithValue("@id", _id);
			cm.Parameters.AddWithValue("@Modelo", _modelo);
			cm.Parameters.AddWithValue("@Marca", _marca);
			if (_ano != 0)
				cm.Parameters.AddWithValue("@Ano", _ano);
			else
				cm.Parameters.AddWithValue("@Ano", DBNull.Value);
			cm.Parameters.AddWithValue("@Placa", _placa);
			cm.Parameters.AddWithValue("@Capacidade", _capacidade);
			if (_idMotorista != 0)
				cm.Parameters.AddWithValue("@idMotorista", _idMotorista);
			else
				cm.Parameters.AddWithValue("@idMotorista", DBNull.Value);
		}

		private void UpdateChildren(SqlConnection cn)
		{
		}
		#endregion //Data Access - Update

		#region Data Access - Delete
		internal void DeleteSelf(SqlConnection cn)
		{
			if (!IsDirty) return;
			if (IsNew) return;

			ExecuteDelete(cn, new Criteria(_id));
			MarkNew();
		}
		#endregion //Data Access - Delete
		#endregion //Data Access
	}
}
